package com.rzjm.api.netty.water.business.inhandler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rzjm.api.entity.DeviceWater;
import com.rzjm.api.netty.water.NettyUtil;
import com.rzjm.api.netty.water.entity.ReceiveData;
import com.rzjm.api.service.IDeviceWaterMessagesService;
import com.rzjm.api.service.IDeviceWaterService;
import com.rzjm.api.util.MathUtil;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

import static com.rzjm.api.netty.water.constant.SendRtEnum.SEND_RT_99;

/**
 *  设备心跳
 * @author Mr.Zhou
 * @Description:
 * @date 2025/3/17 9:27
 */
@Component
public class Receive1InHandler implements InHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(Receive1InHandler.class);
    @Autowired
    private IDeviceWaterService devicesService;
    @Autowired
    private IDeviceWaterMessagesService deviceMessagesService;


    @Override
    public void handler(ChannelHandlerContext ctx, ReceiveData receiveData) {
        //保存Channel
        NettyUtil.addChannel(ctx, receiveData.getId());
        // 保存上报数据日志
        Optional.ofNullable(getMessage(receiveData))
                .ifPresent(message -> deviceMessagesService.save(message));

        DeviceWater deviceWater = devicesService.findById(receiveData.getId());
        //回复消息
        String replyData = requestData(deviceWater, receiveData);
        if (StrUtil.isNotEmpty(replyData)) {
            reply(replyData, receiveData.getId());
        }
    }

    /**
     * 拼装数据
     * @param device
     * @param receiveData
     * @return
     */
    private String requestData(DeviceWater device, ReceiveData receiveData) {
//        DeviceWater device = devicesService.findById(deviceWater.getId());
        if (device == null) {
            return "{\"rt\":99,\"v1\":1}";
        }
        System.out.println("心跳数据请求：" + JSONUtil.toJsonStr(receiveData));
        String replyData;
        // 当日开始时间的总秒数
//        long startSecond = localDateTimeStartToSecond();
        JSONObject obj = JSONUtil.createObj();

        obj.set("rt", SEND_RT_99.getRt());
        obj.set("v1", receiveData.getV1());//设备状态 0 - 有故障 1 - 正常运行
        obj.set("v2", receiveData.getV2());//错误码
        obj.set("v3", receiveData.getV3());//水位状态 001 - 低水位 010 - 中水位 100 - 高水位
        obj.set("v4", receiveData.getV4());//超声波测距 超声波到液面的距离
        obj.set("v5", receiveData.getV5());//设备温度 例如 235
        obj.set("v6", receiveData.getV6());//取水仓人体感应 0 - 有人 1 - 没人
        obj.set("v7", receiveData.getV7());//按钮状态 001 - 开启 - 010 暂停 100 - 清洗
        obj.set("v8", receiveData.getV8());//灯箱开关 0 - 关闭 1 - 开启

        if(receiveData.getV1().equals("1")){
            device.setState(1);
        }else{
            device.setState(3);
            device.setErrorTime(new Date());
        }

//        1：水位过低
//        2：低水位
//        3：中水位
//        4：高水位
        if(StrUtil.isNotEmpty(receiveData.getV3())){
            device.setTankState(Integer.parseInt(receiveData.getV3()));
        }

        double temperature = MathUtil.getDoubleUp( Double.parseDouble(receiveData.getV5()) / 10d);
        device.setTemperature(temperature);
        device.setLastOnlineTime(new Date());
        devicesService.updateById(device);

        replyData = JSONUtil.toJsonStr(obj);
        return replyData;
    }
}
